package com.meter.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meter.basic.domain.BasicDevice;
import com.meter.basic.domain.BasicHouse;
import com.meter.basic.domain.BasicMeter;
import com.meter.basic.mapper.BasicDeviceMapper;
import com.meter.basic.mapper.BasicHouseMapper;
import com.meter.basic.mapper.BasicMeterMapper;
import com.meter.basic.service.IBasicDeviceService;
import com.meter.basic.service.IBasicMeterService;
import com.meter.common.constant.UserConstants;
import com.meter.common.core.text.Convert;
import com.meter.common.exception.ServiceException;
import com.meter.common.utils.DateUtils;
import com.meter.common.utils.StringUtils;
import com.meter.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class BasicMeterServiceImpl extends ServiceImpl<BasicMeterMapper, BasicMeter> implements IBasicMeterService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BasicDeviceMapper basicDeviceMapper;

    @Autowired
    private BasicHouseMapper basicHouseMapper;

    public BasicMeter selectBasicMeterById(Long meterId) {
        return baseMapper.selectBasicMeterById(meterId);
    }

    public List<BasicMeter> selectBasicMeterList(BasicMeter basicMeter) {
        List<BasicMeter> meterList = baseMapper.selectBasicMeterList(basicMeter);
        for (BasicMeter meter : meterList) {
            if (redisService.hHasKey("sys-netty", meter.getDeviceCode())) {
                meter.setOnlineStatus("online");
            } else {
                meter.setOnlineStatus("offline");
            }
        }
        return meterList;
    }

    public int insertBasicMeter(BasicMeter basicMeter) {
        basicMeter.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicMeter);
    }

    public int updateBasicMeter(BasicMeter basicMeter) {
        basicMeter.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicMeter);
    }

    public boolean checkMeterNoUnique(BasicMeter basicMeter) {
        Long meterId = StringUtils.isNull(basicMeter.getMeterId()) ? -1L : basicMeter.getMeterId();
        BasicMeter info = baseMapper.selectOne(new LambdaQueryWrapper<BasicMeter>().eq(BasicMeter::getMeterNo, basicMeter.getMeterNo()));
        if (StringUtils.isNotNull(info) && info.getMeterId().longValue() != meterId.longValue())
            return UserConstants.NOT_UNIQUE;
        return UserConstants.UNIQUE;
    }

    public int deleteBasicMeterByIds(String meterIds) {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(meterIds)));
    }

    public int deleteBasicMeterById(Long meterId) {
        return baseMapper.deleteById(meterId);
    }

    /**
     * 导入热表信息数据
     *
     * @param meterList 热表信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importBaseMeter(List<BasicMeter> meterList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(meterList) || meterList.size() == 0)
        {
            throw new ServiceException("导入热表信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicMeter basicMeter : meterList)
        {
            try
            {
                Long houseId = 0L;
                if(StringUtils.isNotEmpty(basicMeter.getHouseName())) {
                    BasicHouse houseInfo = basicHouseMapper.selectOne(Wrappers.lambdaQuery(BasicHouse.class)
                            .eq(BasicHouse::getHouseName, basicMeter.getHouseName()));
                    if(StringUtils.isNotNull(houseInfo)) {
                        houseId = houseInfo.getHouseId();
                    }
                }

                if(StringUtils.isNotNull(basicMeter.getDeviceCode())) {
                    BasicDevice deviceInfo = basicDeviceMapper.selectOne(Wrappers.lambdaQuery(BasicDevice.class)
                            .eq(BasicDevice::getDeviceCode, basicMeter.getDeviceCode()));
                    if(StringUtils.isNotNull(deviceInfo)) {
                        basicMeter.setDeviceId(deviceInfo.getDeviceId());
                    }
                }

                BasicMeter meterInfo = baseMapper.selectOne(Wrappers.lambdaQuery(BasicMeter.class)
                        .eq(BasicMeter::getMeterNo, basicMeter.getMeterNo()));
                if(StringUtils.isNull(meterInfo)) {
                    basicMeter.setHouseId(houseId);
                    basicMeter.setCreateBy(operName);
                    this.insertBasicMeter(basicMeter);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、热表信息 " + basicMeter.getMeterNo() + " 导入成功");
                } else if(isUpdateSupport) {
                    basicMeter.setMeterId(meterInfo.getMeterId());
                    basicMeter.setUpdateBy(operName);
                    this.updateBasicMeter(basicMeter);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、热表信息 " + basicMeter.getMeterNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、热表信息 " + basicMeter.getMeterNo() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、热表信息 " + basicMeter.getMeterNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
